package com.niodata.dp.web.module.task;

import com.niodata.dp.log.LogUtil;
import com.niodata.dp.task.entity.TaskInfo;
import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.scheduling.support.CronExpression;

public class TaskInfoVo extends TaskInfo {

  private static final Logger logger = Logger.getLogger(TaskInfoVo.class);

  private Date nextTime;

  public static List<TaskInfoVo> buildFromTaskInfo(List<TaskInfo> taskInfoList) {
    return taskInfoList.stream().map(new Function<TaskInfo, TaskInfoVo>() {
      @Override
      public TaskInfoVo apply(TaskInfo taskInfo) {
        return buildFromTaskInfo(taskInfo);
      }
    }).collect(Collectors.toList());
  }

  /**
   * build TaskInfoVo from TaskInfo.
   *
   * @param taskInfo task info
   * @return task info vo
   */
  public static TaskInfoVo buildFromTaskInfo(TaskInfo taskInfo) {
    TaskInfoVo vo = new TaskInfoVo();
    try {
      BeanUtils.copyProperties(vo, taskInfo);
    } catch (IllegalAccessException e) {
      LogUtil.logStackTrace(logger, e);
    } catch (InvocationTargetException e) {
      LogUtil.logStackTrace(logger, e);
    }
    if (taskInfo.isScheduled()) {
      CronExpression generator = CronExpression.parse(taskInfo.getScheduleCron());
      LocalDateTime nextTime = generator.next(LocalDateTime.now());
      ZonedDateTime zonedDateTime = nextTime.atZone(ZoneId.systemDefault());
      vo.nextTime = Date.from(zonedDateTime.toInstant());
    }

    return vo;
  }

  public Date getNextTime() {
    return nextTime;
  }

  public void setNextTime(Date nextTime) {
    this.nextTime = nextTime;
  }
}
